<template>
    <div class="countdown-box">
        <a class="code-btn" :class="{'disabled': disabled}" @click="!disabled ? getCode() : ''" v-text="countdownConfig.btnText"></a>
    </div>
</template>

<script>

export default {
    data() {
        return {
            defaultTime: '',
            disabled: false
        }
    },
    props: {
        countdownConfig: {
            type: Object
        }
    },
    destroyed() {
        clearInterval(this.timer)
    },
    methods: {
        getCode() {
            this.defaultTime = this.countdownConfig.time
            this.countDown()
        },
        // 倒计时
        countDown(){
            if (this.disabled) {
                return false;
            }

            // 倒计时开始后按钮置灰
            this.disabled = true

            this.timer = setInterval(() => {
                this.countdownConfig.btnText = `${this.countdownConfig.time}s可重发`
                this.countdownConfig.time--
                if (this.countdownConfig.time < 0) {
                    this.disabled = false
                    this.countdownConfig.btnText = this.countdownConfig.resetText
                    this.countdownConfig.time = this.defaultTime
                    clearInterval(this.timer)
                    this.$emit('end')
                }
            }, 1000)
            return
        }
    }
}
</script>

<style>
.countdown-box {
    display: inline-block;
    height: 38px;
    line-height: 38px;
    border-radius: 4px;
    overflow: hidden;
}
.countdown-box .code-btn {
    height: inherit;
    display: inline-flex;
    align-items: center;
    padding: 0 15px;
    color: #fff;
    font-size: 14px;
    border-radius: 4px;
    background-color: #EF1F1F;
    cursor: pointer;
}
.countdown-box .disabled {
    opacity: .5;
    cursor: no-drop;
}
</style>